package org.jeecg.modules.flow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.base.entity.LoginRole;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flow.entity.ActRuTask;
import org.jeecg.modules.flow.mapper.ActRuTaskMapper;
import org.jeecg.modules.flow.query.TaskQuery;
import org.jeecg.modules.flow.service.IActRuTaskService;
import org.jeecg.modules.flow.vo.TaskVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: ru_task
 * @Author: jeecg-boot
 * @Date: 2021-12-28
 * @Version: V1.0
 */
@Service
public class ActRuTaskServiceImpl extends ServiceImpl<ActRuTaskMapper, ActRuTask> implements IActRuTaskService {

    @Resource
    private ActRuTaskMapper actRuTaskMapper;


    @Override
    public Page<TaskVo> findTasks(TaskQuery query, Integer pageNo, Integer pageSize) {
        LoginUser user = getUser();
        // 查询用户机构
        String orgId = user.getOrganization().getOrganizationId();
        // 获取用户的客户号
        Integer cusNo = user.getCusNo() != null ? user.getCusNo() : 0;
        // 用户角色列表
        List<String> roles = user.getRoles().stream().map(LoginRole::getRoleCode).collect(Collectors.toList());
        QueryWrapper<ActRuTask> queryWrapper = new QueryWrapper<>();
        queryWrapper
                // 如果业务字段不为空则模块匹配
                .like(StringUtils.isNotBlank(query.getBusinessKey()), "E.BUSINESS_KEY_", query.getBusinessKey())
                // 如果流程实例名称不为空则模糊匹配
                .like(StringUtils.isNotBlank(query.getProcessInstanceName()), "E.NAME_", query.getProcessInstanceName())
                // 只获取指定流程实例ID下的任务
                .eq(StringUtils.isNotBlank(query.getProcessInstanceId()), "RES.PROC_INST_ID_", query.getProcessInstanceId())
                // 获取流程变量org 为指定机构的任务
                .and(q -> q.eq("ARV.NAME_", "orgId").eq("ARV.TYPE_", "string").eq("ARV.TEXT_", orgId))
                // 获取流程变量cusNo 为指定核心企业的任务
                .or(q -> q.eq("ARV.NAME_", "cusNo").eq("ARV.TYPE_", "integer").eq("ARV.LONG_", cusNo))
                // 获取当前用户的任务，个人、角色
                .and(q -> q.eq("FP.candidate_users", user.getId()).or().in("FP.candidate_groups", roles))
                .orderByAsc("RES.CREATE_TIME_");

        return actRuTaskMapper.findTasks(queryWrapper, new Page<>(pageNo, pageSize));
    }


    public LoginUser getUser() {
        return (LoginUser) SecurityUtils.getSubject().getPrincipal();
    }

}
